package org.jspar.matrix;

import org.jspar.model.Module;
import org.jspar.model.NetList;
import org.jspar.model.Terminal;

public class ForwardMatrixBuilder implements IMatrixBuilder {

    public ForwardMatrixBuilder() {
    }

    public ConnectionMatrix build(NetList netList) {
        Module[] modules = netList.modules();
        ConnectionMatrix matrix = new ConnectionMatrix(modules);

        for (int i = 0; i < modules.length; ++i) {
            Terminal[] mterms = modules[i].terminals();
            for (int j = 0; j < mterms.length; ++j) {
                if (mterms[j].isOut() || mterms[j].isInOut()) {
                    if (mterms[j].net() == null) {
                        System.out.println("module " + modules[i].name() + "("
                                + j + ") not connected");
                        continue;
                    }
                    Terminal[] nterms = mterms[j].net().terminals();
                    for (int k = 0; k < nterms.length; ++k) {
                        if ((nterms[k].isIn() || nterms[k].isInOut())
                                && modules[i] != nterms[k].module()) {
                            matrix.incrementAt(modules[i], nterms[k].module());
                            matrix.incrementAt(modules[i], modules[i]);
                        }
                    }
                }
            }
        }
        return matrix;
    }
}
